package com.wealth.system.web.controller;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

import org.apache.log4j.Logger;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.IncorrectCredentialsException;
import org.apache.shiro.authc.UnknownAccountException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.subject.Subject;
import org.apache.shiro.web.util.SavedRequest;
import org.apache.shiro.web.util.WebUtils;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import com.wealth.member.entity.Member;
import com.wealth.system.service.ShiroMember;

import iaas.annotation.Log;
import iaas.enums.StatusEnum;

/**
 * 登录
 * @author chan
 */

@Controller
@RequestMapping(value="/login")
public class LoginController extends BaseController{
	
	Logger logger = Logger.getLogger(LoginController.class);
	
	@RequestMapping(method=RequestMethod.GET)
	public String login(HttpServletRequest request){
		return "login";
	}
	
	/**
	 * 用户登录
	 */	
	@Log(method="登录")
	@RequestMapping(method = RequestMethod.POST)
	public String login(Member member,HttpSession session,HttpServletRequest request,Model model,RedirectAttributes redirectAttributes){
		
//		String code = (String) session.getAttribute("validateCode");
//		String summitCode = request.getParameter("validateCode");
		String error = null;
		UsernamePasswordToken token = null;
		Subject users = null;
		try { 
			/*
			 if(StringUtils.isEmpty(summitCode) || !StringUtils.equals(code.toLowerCase(), summitCode.toLowerCase())){
				 model.addAttribute("msg", "验证码错误");
				 return "/login";
			 }
			 */
			 users = SecurityUtils.getSubject();
			 token = new UsernamePasswordToken(member.getUsername(),member.getPassword());
			 token.setRememberMe(true);
			 users.login(token); 
			//登录成功访问首页
			 
			//判断用户状态 
			 int status = ShiroMember.getInstance().getMember().getStatus();
			 if(status==StatusEnum.DELETE.getValue()){
		    		model.addAttribute("msg", "用户不存在，请联系管理员解决");
					return "/login";
			 }
			 if(status==StatusEnum.STOP.getValue()){
		    		model.addAttribute("msg", "用户被停用，请联系管理员解决");
					return "/login";
			 }
			 
			
	     } catch (UnknownAccountException e) {  
	    	 e.printStackTrace();
	            error = "用户名/密码错误";  
	     } catch (IncorrectCredentialsException e) {  
	            error = "用户名/密码错误";  
	     } catch (AuthenticationException e) {  
	            //其他错误，比如锁定，如果想单独处理请单独catch处理  
	            error = "其他错误：" + e.getMessage();  
	     }catch (NullPointerException e) {
	    	 error = "验证码错误";  
	     }catch (Exception e) {
	    	 error = "系统错误,请联系管理员" ;  
		} 
		
		//错误了，返回登录页面  
	     if(error != null) {
	    	if(token!=null){
	    		token.clear();
	    	}
	        model.addAttribute("msg", error);
			return "login";
	     } 
	     SavedRequest srequest = WebUtils.getAndClearSavedRequest(request);
	     if (srequest != null) {
				String redirect = srequest.getRequestUrl().replaceAll(
						request.getContextPath(), "");
//				System.out.println(request.getContextPath());
//				System.out.println(request.getLocalAddr());
//				System.out.println(request.getRequestURI());
//				System.out.println(request.getServletPath());
//				System.out.println(redirect);
				return "redirect:" + redirect;
			} else {
				 return "redirect:/";
			} 
	}
	
}
